import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { LoginUserVO } from '../models/LoginUserVO'
import type { UserLoginRequest } from '../models/UserLoginRequest'
import type { UserRegisterRequest } from '../models/UserRegisterRequest'
import { UserControllerService } from '../services/UserControllerService'
import { ElMessage } from 'element-plus'
import { configureOpenAPI } from '../utils/apiConfig'

export const useUserStore = defineStore('user', () => {
  // 状态
  const currentUser = ref<LoginUserVO | null>(null)
  const token = ref<string>('')
  
  // 计算属性
  const isLoggedIn = computed(() => !!token.value && !!currentUser.value)
  
  // 内部方法：配置API和保存状态
  const updateAuthState = (user: LoginUserVO | null, newToken: string = '') => {
    currentUser.value = user
    token.value = newToken
    configureOpenAPI()
    console.log('用户状态已更新:', { user: user?.userName, token: !!newToken })
  }

  // 登录
  const login = async (loginRequest: UserLoginRequest) => {
    try {
      console.log('开始登录...')
      const response = await UserControllerService.userLogin(loginRequest)
      if (response.code === 0 && response.data) {
        updateAuthState(response.data, response.data.token || '')
        ElMessage.success('登录成功')
        return true
      } else {
        ElMessage.error(response.message || '登录失败')
        return false
      }
    } catch (error: any) {
      console.error('登录失败:', error)
      ElMessage.error(error.message || '登录失败')
      return false
    }
  }

  // 注册
  const register = async (registerRequest: UserRegisterRequest) => {
    try {
      const response = await UserControllerService.userRegister(registerRequest)
      if (response.code === 0) {
        ElMessage.success('注册成功，请登录')
        return true
      } else {
        ElMessage.error(response.message || '注册失败')
        return false
      }
    } catch (error: any) {
      ElMessage.error(error.message || '注册失败')
      return false
    }
  }

  // 登出
  const logout = async () => {
    try {
      await UserControllerService.userLogout()
    } catch (error) {
      console.error('登出请求失败:', error)
    } finally {
      // 无论请求是否成功，都清除本地状态
      updateAuthState(null, '')
      ElMessage.success('已退出登录')
    }
  }

  // 获取当前登录用户信息
  const getCurrentUser = async (): Promise<LoginUserVO | null> => {
    // 如果已经有用户数据且token有效，直接返回
    if (currentUser.value && token.value) {
      console.log('使用缓存的用户数据:', currentUser.value.userName)
      return currentUser.value
    }
    
    try {
      console.log('从服务器获取用户信息...')
      const response = await UserControllerService.getLoginUser()
      if (response.code === 0 && response.data) {
        // 更新用户信息，保留现有token（如果后端返回的token为null）
        const newToken = response.data.token || token.value
        updateAuthState(response.data, newToken)
        console.log('用户信息获取成功:', response.data.userName)
        return response.data
      } else {
        console.warn('获取用户信息失败:', response.message)
        updateAuthState(null, '')
        return null
      }
    } catch (error) {
      console.error('获取用户信息失败:', error)
      updateAuthState(null, '')
      return null
    }
  }
  
  // 强制刷新用户信息
  const refreshCurrentUser = async (): Promise<LoginUserVO | null> => {
    try {
      console.log('强制刷新用户信息...')
      const response = await UserControllerService.getLoginUser()
      if (response.code === 0 && response.data) {
        const newToken = response.data.token || token.value
        updateAuthState(response.data, newToken)
        console.log('用户信息刷新成功:', response.data.userName)
        return response.data
      } else {
        console.warn('刷新用户信息失败:', response.message)
        return null
      }
    } catch (error) {
      console.error('刷新用户信息失败:', error)
      return null
    }
  }

  return {
    currentUser,
    token,
    isLoggedIn,
    login,
    register,
    logout,
    getCurrentUser,
    refreshCurrentUser
  }
}, {
  persist: true
})
